package com.hzy.chinese.jchess.ui.activity;

import android.app.Activity;
import android.content.Intent;
import android.os.Looper;
import android.support.annotation.NonNull;
import android.os.Bundle;
import android.text.TextUtils;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;

import com.avos.avoscloud.AVException;
import com.avos.avoscloud.AVObject;
import com.avos.avoscloud.AVUser;
import com.avos.avoscloud.SignUpCallback;
import com.blankj.utilcode.util.RegexUtils;
import com.blankj.utilcode.util.ToastUtils;
import com.hzy.chinese.jchess.R;
import com.hzy.chinese.jchess.ui.activity.base.AbstractActionBarActivity;
import com.hzy.chinese.jchess.ui.dialog.DoingDialog;
import com.hzy.chinese.jchess.utils.DbUtil;
import com.hzy.chinese.jchess.utils.KeySet;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;
import io.reactivex.annotations.Nullable;

public class RegisterActivity extends AbstractActionBarActivity {

    @BindView(R.id.edt_username) EditText edt_username;
    @BindView(R.id.edt_email) EditText edt_email;
    @BindView(R.id.edt_password) EditText edt_password;
    @BindView(R.id.edt_verifyPwd) EditText edt_verifyPwd;
    @BindView(R.id.btn_register) Button btn_register;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        ButterKnife.bind(this);
        initView();
    }

    private void initView() {
        Intent intent = getIntent();
        String username = intent.getStringExtra(KeySet.Intent.KEY_USERNAME);
        if(username != null){
            edt_username.setText(username);
        }

    }

    @OnClick({R.id.btn_register})
    public void onClick(View view){
        switch (view.getId()){
            case R.id.btn_register:{
                actionRegister();
            } break;
            default:
        }
    }

    private void actionRegister() {
        String username = edt_username.getText().toString().trim();
        String email = edt_email.getText().toString().trim();
        String password = edt_password.getText().toString().trim();
        String verifyPwd = edt_verifyPwd.getText().toString().trim();
        boolean cancel = false;
        View focusView = null;
        if(TextUtils.isEmpty(username)){
            edt_username.setError(getResources().getString(R.string.error_empty_username));
            cancel = true;
            focusView = edt_username;
        }else if(!(username.length() >= 6 && username.length() <= 12)){
            edt_username.setError(getResources().getString(R.string.error_username_length));
            cancel = true;
            focusView = edt_username;
        }

        if(!RegexUtils.isEmail(email)){
            edt_email.setError(getResources().getString(R.string.error_invalid_email));
            cancel = true;
            focusView = edt_email;
        }

        if(TextUtils.isEmpty(password)){
            edt_password.setError(getResources().getString(R.string.error_empty_password), null);
            cancel = true;
            focusView = edt_password;
        } else if(password.length() < 6){
            edt_password.setError(getResources().getString(R.string.error_password_length), null);
            cancel = true;
            focusView = edt_password;

        } else if(!password.equals(verifyPwd)){
            edt_verifyPwd.setError(getResources().getString(R.string.error_Inconsistent_pwd), null);
            cancel = true;
            focusView = edt_verifyPwd;
        }
        if(cancel){
            focusView.requestFocus();
        }else{
            registerLogic(username, email, password);
        }

    }

    private boolean registering = false;

    private void registerLogic(final String username, String email, final String password){
        if(registering) {
            return;
        }
        registering = true;
        postShowDialog(getResources().getString(R.string.on_request_server));
        DbUtil.registerUser(username, email, password, new SignUpCallback() {
            @Override
            public void done(AVException e) {
                postDismissDialog();
                registering = false;
                if(e == null){
                    ToastUtils.showShort(getResources().getString(R.string.register_success));
                    finishRegister(username, password);
                }else{
                    ToastUtils.showShort(String.format(getResources().getString(R.string.register_fail), e.getMessage()));
                    Log.d("CYY", "done:"+e.getMessage());
                }
            }
        });
    }


    private void finishRegister(String username, String password){
        //这种回传数据的方式有安全缺陷
        Intent intent = new Intent();
        intent.putExtra(KeySet.Intent.KEY_USERNAME, username);
        intent.putExtra(KeySet.Intent.KEY_PASSWORD, password);
        setResult(RESULT_OK, intent);
        finish();
    }

    public void postShowDialog(final String message){

        if(Looper.myLooper() == Looper.getMainLooper()){
            DoingDialog.newInstance().
                    withMessage(message)
                    .show(getSupportFragmentManager(), DoingDialog.TAG);
        }else{
            getWindow().getDecorView().post(new Runnable() {
                @Override
                public void run() {
                    postShowDialog(message);
                }
            });
        }
    }

    public void postDismissDialog(){
        if(Looper.myLooper() == Looper.getMainLooper()){
            DoingDialog.newInstance().dismiss();
        }else{
            getWindow().getDecorView().post(new Runnable() {
                @Override
                public void run() {
                    postDismissDialog();
                }
            });
        }

    }

    @Override
    protected int getlayoutResId() {
        return R.layout.activity_register;
    }


    public static void launchActivity(@NonNull Activity activity, @Nullable String username){
        Intent intent = new Intent(activity, RegisterActivity.class);
        if(!TextUtils.isEmpty(username)){
            intent.putExtra(KeySet.Intent.KEY_USERNAME, username);
        }
        activity.startActivity(intent);
    }

    public static void launchActivityForResult(@NonNull Activity activity, int requestCode,  @Nullable String username){
        Intent intent = new Intent(activity, RegisterActivity.class);
        if(!TextUtils.isEmpty(username)){
            intent.putExtra(KeySet.Intent.KEY_USERNAME, username);
        }
        activity.startActivityForResult(intent, requestCode);
    }
}
